<?php

namespace App\Http\Middleware;

use App\Helpers\ApiResponseTrait;
use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;

class authJWT
{
    use ApiResponseTrait;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try{
            JWTAuth::parseToken()->authenticate();
        }catch (\Exception $e) {
            if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
                return $this->failed('Token 无效', 401);
            } else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
                return $this->failed('Token 已过期', 401);
            } else {
                return$this->failed($e->getMessage(), 401);
            }
        }
        return $next($request);
    }
}
